<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\model;

/**
 * 广告操作日志模型
 */
class AdvertisementLog extends ModelBase
{
    // 表名

    
    // 自动时间戳
    protected $autoWriteTimestamp = 'datetime';
    
    // 时间字段
    protected $createTime = 'create_time';
    protected $updateTime = false; // 日志表不需要更新时间
    
    // 字段类型转换
    protected $type = [
        'id' => 'integer',
        'ad_id' => 'integer',
        'user_id' => 'integer',
        'create_time' => 'datetime',
    ];
    
    // 操作类型常量
    const ACTION_VIEW = 'view';   // 浏览
    const ACTION_CLICK = 'click'; // 点击
    
    /**
     * 获取操作类型选项
     */
    public static function getActionOptions()
    {
        return [
            self::ACTION_VIEW => '浏览',
            self::ACTION_CLICK => '点击',
        ];
    }
    
    /**
     * 获取操作类型文本
     */
    public function getActionTextAttr($value = null, $data = [])
    {
        $options = self::getActionOptions();
        return $options[$data['action']] ?? '未知';
    }
    
    /**
     * 记录广告操作日志
     * @param int $adId 广告ID
     * @param string $action 操作类型
     * @param int $userId 用户ID，0表示未登录用户
     * @param string $ip IP地址
     * @param string $userAgent 用户代理
     * @return bool
     */
    public function addLog($adId, $action = self::ACTION_VIEW, $userId = 0, $ip = '', $userAgent = '')
    {
        $data = [
            'ad_id' => $adId,
            'user_id' => $userId,
            'action' => $action,
            'ip' => $ip ?: request()->ip(),
            'user_agent' => $userAgent ?: request()->header('User-Agent', ''),
        ];
        
        return $this->setInfo($data);
    }
    
    /**
     * 记录广告浏览日志
     * @param int $adId 广告ID
     * @param int $userId 用户ID
     * @param string $ip IP地址
     * @param string $userAgent 用户代理
     * @return bool
     */
    public function addViewLog($adId, $userId = 0, $ip = '', $userAgent = '')
    {
        return $this->addLog($adId, self::ACTION_VIEW, $userId, $ip, $userAgent);
    }
    
    /**
     * 记录广告点击日志
     * @param int $adId 广告ID
     * @param int $userId 用户ID
     * @param string $ip IP地址
     * @param string $userAgent 用户代理
     * @return bool
     */
    public function addClickLog($adId, $userId = 0, $ip = '', $userAgent = '')
    {
        return $this->addLog($adId, self::ACTION_CLICK, $userId, $ip, $userAgent);
    }
    
    /**
     * 获取广告统计数据
     * @param int $adId 广告ID，0表示所有广告
     * @param string $action 操作类型，空表示所有操作
     * @param string $startDate 开始日期
     * @param string $endDate 结束日期
     * @return array
     */
    public function getStatistics($adId = 0, $action = '', $startDate = '', $endDate = '')
    {
        $where = [];
        
        // 添加广告ID条件
        if ($adId > 0) {
            $where['ad_id'] = $adId;
        }
        
        // 添加操作类型条件
        if (!empty($action)) {
            $where['action'] = $action;
        }
        
        // 添加日期范围条件
        if (!empty($startDate)) {
            $where[] = ['create_time', '>=', $startDate . ' 00:00:00'];
        }
        if (!empty($endDate)) {
            $where[] = ['create_time', '<=', $endDate . ' 23:59:59'];
        }
        
        return [
            'total_count' => $this->stat($where, 'count'),
            'view_count' => $this->stat(array_merge($where, ['action' => self::ACTION_VIEW]), 'count'),
            'click_count' => $this->stat(array_merge($where, ['action' => self::ACTION_CLICK]), 'count'),
        ];
    }
    
    /**
     * 获取广告点击率
     * @param int $adId 广告ID
     * @param string $startDate 开始日期
     * @param string $endDate 结束日期
     * @return float
     */
    public function getClickRate($adId, $startDate = '', $endDate = '')
    {
        $stats = $this->getStatistics($adId, '', $startDate, $endDate);
        
        if ($stats['view_count'] == 0) {
            return 0;
        }
        
        return round(($stats['click_count'] / $stats['view_count']) * 100, 2);
    }
    
    /**
     * 获取热门广告排行
     * @param string $action 操作类型
     * @param int $limit 限制数量
     * @param string $startDate 开始日期
     * @param string $endDate 结束日期
     * @return array
     */
    public function getHotAdvertisements($action = self::ACTION_CLICK, $limit = 10, $startDate = '', $endDate = '')
    {
        $where = ['action' => $action];
        
        // 添加日期范围条件
        if (!empty($startDate)) {
            $where[] = ['create_time', '>=', $startDate . ' 00:00:00'];
        }
        if (!empty($endDate)) {
            $where[] = ['create_time', '<=', $endDate . ' 23:59:59'];
        }
        
        // 使用原生SQL查询统计
        $sql = "SELECT ad_id, COUNT(*) as count FROM {$this->getTable()} WHERE " . $this->parseWhere($where) . " GROUP BY ad_id ORDER BY count DESC LIMIT {$limit}";
        
        return $this->dbQuery($sql);
    }
    
    /**
     * 清理过期日志
     * @param int $days 保留天数，默认90天
     * @return bool
     */
    public function cleanExpiredLogs($days = 90)
    {
        $expireDate = date('Y-m-d H:i:s', time() - $days * 86400);
        $where = [['create_time', '<', $expireDate]];
        
        return $this->deleteInfo($where, true);
    }
}